package com.base.themvx.viewholder

import android.graphics.drawable.GradientDrawable
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import androidx.recyclerview.widget.RecyclerView
import com.base.themvx.R
import com.base.themvx.adapter.ACommonViewHolder
import com.base.themvx.adapter.AbsSelectableAdapter
import com.base.themvx.adapter.MenuAdapter
import com.base.themvx.adapter.MenuAdapter.Configs.PAYLOAD_MENU_HINT_COUNT_CHANGED
import com.base.themvx.defNonSyncLazy
import com.base.themvx.model.MenuItemData
import com.base.themvx.utils.CommonBgBuilder
import com.base.themvx.utils.ImageUtil

/**
 * 菜单项 的 itemView 的 [ViewHolder
 */
class MenuItemViewHolder(parentView: ViewGroup) :
    ACommonViewHolder<MenuItemData>(parentView, R.layout.common_menu_item_view),
    View.OnClickListener{

    private lateinit var mTvMenuTitle: TextView
    private lateinit var mTvMsgCount: TextView

    /**
     * 菜单的　Icon
     */
    private lateinit var mIvMenuIcon: ImageView

//    /**
//     * Lottie 动画视图
//     */
//    private lateinit var mIvLottieView: LottieAnimationView

    private val mTitleColorSelected by defNonSyncLazy {
        0xFF9BED82.toInt()
    }

    private val mTitleUnSelected by defNonSyncLazy {
//        0xFFD6D6D6.toInt()
        0xFFA0A3A7.toInt()
    }

    override fun initViews() {
        mTvMsgCount = view(R.id.tvMsgCount)
        mTvMenuTitle = view(R.id.tvTitle)
        mIvMenuIcon = view(R.id.ivIcon)
//        mIvLottieView = view(R.id.ivLottie)
        itemView.setOnClickListener(this)
    }

    private val dp26Px by defNonSyncLazy {
        CommonBgBuilder.mDp1Px * 26
    }
    private val dp15Px by defNonSyncLazy {
        CommonBgBuilder.mDp1Px * 15
    }

    private val dp18Px by defNonSyncLazy {
        CommonBgBuilder.mDp1Px * 18
    }

    /**
     * 菜单项提示消息的背景
     */
    private val mBgOfHintCount by lazy(LazyThreadSafetyMode.NONE){
        val bgDrawable = GradientDrawable()
        bgDrawable.cornerRadius = 0f
        bgDrawable.colors = intArrayOf(0xFFFF4456.toInt(),0xFFFF6A79.toInt())
        bgDrawable.gradientType = GradientDrawable.LINEAR_GRADIENT
        bgDrawable
    }
    /**
     * 绑定数据
     * @param item
     */
    override fun onBindView(item: MenuItemData?) {
        mItemData = item
//        val itemPos = layoutPosition
//        val itemBgColor = if (itemPos % 2 == 0) {
//            Color.CYAN
//        } else Color.BLUE
//        itemView.setBackgroundColor(itemBgColor)
        item?.run {
            if (titleResId != 0){
                mTvMenuTitle.setText(titleResId)
            } else {
                mTvMenuTitle.text = title
            }
            itemView.updateLayoutParams<ViewGroup.MarginLayoutParams> {
                marginEnd = menuMarginNext
                var finalItemWidth: Int? = null
                peekHostAdapter()?.assignItemWidth?.let {wholeItemW ->
                    if (wholeItemW > 0) {
                        finalItemWidth = wholeItemW
                    }
                }
                item.menuWidth?.let {selfW ->
                    if (selfW > 0) {
                        finalItemWidth = selfW
                    }
                }
                finalItemWidth?.let {
                    if (it > 0) {
                        width = it
                    }
                }
            }
            itemView.isInvisible = !isVisiable
            if (!isVisiable) {
                return@run
            }
            var isHasIcon = false
            if (!iconUrl.isNullOrBlank()) {//如果有icon的 url 优先级最高
                mIvMenuIcon.isInvisible = isIconLottieAnim
                if (isIconLottieAnim) {
//                    mIvLottieView.isVisible = true
//                    mIvLottieView.setAnimation(iconUrl)
                } else {
                    ImageUtil.loadImage(mContext,iconUrl,0,0,mIvMenuIcon)
                }
                isHasIcon = true
            } else {// 非 url icon 资源
//                mIvLottieView.isVisible = false
                iconDrawableRes?.let {
                    mIvMenuIcon.setImageResource(it)
                    isHasIcon = true
                }
            }
            if (!isHasIcon) {//如果 本 menu没有 icon资源
                mIvMenuIcon.isVisible = false
//                mIvLottieView.isVisible = false
            }
            checkSelectedState(false)
//            updateMenuHintCount()
        }
    }

    /**
     * 更新菜单项提示消息数量
     */
    private fun updateMenuHintCount() {
        mItemData?.run {
            mTvMsgCount.run {
                if (background == null) {
                    mBgOfHintCount.shape = GradientDrawable.OVAL
                    background = mBgOfHintCount
                }
                isVisible = if (msgHintCount > 0) {
                    text = if (msgHintCount > 99) {
                        if (width != dp26Px) {
                            updateLayoutParams<ViewGroup.LayoutParams> {
                                width = dp26Px
                            }
                            mBgOfHintCount.cornerRadius = dp18Px.toFloat()
                            mBgOfHintCount.shape = GradientDrawable.RECTANGLE
                            background = mBgOfHintCount
                        }
                        "99+"
                    } else {//100以下
                        if (width != dp15Px) {
                            updateLayoutParams<ViewGroup.LayoutParams> {
                                width = dp15Px
                            }
                            mBgOfHintCount.cornerRadius = 0f
                            mBgOfHintCount.shape = GradientDrawable.OVAL
                            background = mBgOfHintCount
                        }
                        "$msgHintCount"
                    }
                    true
                } else {//提示消息数为 < 1
                    false
                }
            }//run end of mTvMsgCount
        }
    }

    private fun peekHostAdapter(): AbsSelectableAdapter<MenuItemData, *>? {
        return mHostAdapter as AbsSelectableAdapter<MenuItemData, *>?
    }

    private fun checkSelectedState(isTrrigerFromPayLoad: Boolean) {
        val isItemSelected = peekHostAdapter()?.isTheItemSelected(mItemData) ?: false
        mTvMenuTitle.setTextColor(
            if (isItemSelected) {
                mTitleColorSelected
            } else {
                mTitleUnSelected
            }
        )
        //如果有动画的话，需要播放或者停止播放动画 todo
//        if (mIvIconLocal.isVisible) {
//            mIvIconLocal.isSelected = isItemSelected
//        }
        //lottie 动画的控件显示了
//        if (mIvLottieView.isVisible) {
//            mItemData?.isIconLottieAnim?.let {isLottieAnim ->
//                if (isLottieAnim) {
//                    if (mIvLottieView.isAnimating) {
//                        mIvLottieView.cancelAnimation()
//                    }
//                    if (isItemSelected) {
//                        mIvLottieView.playAnimation()//每选中一次，则重新播放动画一次
//                    } else {//未选中的，恢复到 动画第一帧，置灰
//                        mIvLottieView.frame = 0
//                    }
//                }
//            }
//        }
        mIvMenuIcon.isSelected = isItemSelected
    }

    override fun onBindView(item: MenuItemData?, payloads: List<Any>) {
        mItemData = item
        if (payloads.isNullOrEmpty()) {
            super.onBindView(item, payloads)
            return
        }
        payloads.forEach { payload ->
            when (payload) {
                AbsSelectableAdapter.PAYLOAD_SELECTED_STATE_CHANGED -> {
                    checkSelectedState(true)
                }
                PAYLOAD_MENU_HINT_COUNT_CHANGED -> {//更新 提醒消息数量
                    updateMenuHintCount()
                }
                else -> {}
            }
        }
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    override fun onClick(v: View?) {
        if (v == null) {
            return
        }
        val curPos = adapterPosition
        if (curPos == RecyclerView.NO_POSITION){
            return
        }
        var isDoubleClick = false
        val now = System.currentTimeMillis()
        //消费AB双击事件，避免BC判定为双击事件
        if ((now - mLastTouchDownTime) <= 200) {
            isDoubleClick = true
        } else {
            mLastTouchDownTime = now
        }
        handleItemClick(isDoubleClick)
    }

    private var mLastTouchDownTime = 0L

    private fun handleItemClick(isDoubleClick: Boolean) {
        val curPos = adapterPosition
        if (curPos == RecyclerView.NO_POSITION){
            return
        }
        peekHostAdapterAsDesired<MenuAdapter>()?.let {
            it.mOnItemMultyClickListener?.onItemMultyClick(it, isDoubleClick, itemView, curPos)
        }
    }
}